<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // pending（等待态）、fulfilled（成功态）、rejected（失败态）
        var MyPromise = function(func) {
            let _this = this // 缓存指针
            _this.status = "pending" // 初始的状态
            _this.successValue = undefined // 成功时候的值
            _this.errorValue = undefined // 失败时候的值
            _this.onResolvedCallbacks = [] // 缓存成功回调
            _this.onRejectedCallbacks = [] // 缓存失败回调

            function resolve(value) {
                if (_this.status === 'pending') {
                    _this.status = 'resolved' // 保存成功状态    pending==>可转resolved resolved不可逆转pending
                    _this.successValue = value // 保存成功的值   
                    _this.onResolvedCallbacks.forEach(fn => fn());
                }
            }

            function reject(value) {
                if (_this.status === 'pending') {
                    _this.status = 'rejected' // 保存失败的状态   pending==>可转rejected   rejected不可逆转 
                    _this.errorValue = value
                    _this.onRejectedCallbacks.forEach(fn => fn())
                }
            }
            try {
                func(resolve, reject)
            } catch (error) {
                reject(error)
            }
        }

        MyPromise.prototype.then = function(onFulfilled, onRejected) {
            let _this = this
            if (_this.status === 'pending') { // 调用then的时候如果是pending  就报错函数
                _this.onResolvedCallbacks.push(function() {
                    onFulfilled(_this.successValue)
                })
                _this.onRejectedCallbacks.push(function() {
                    onRejected(_this.errorValue)
                })
            }
        }

        let myPro = new MyPromise(function(resolve, reject) {
            setTimeout(() => {
                resolve('成功test')
                    // reject('失败测试')
            }, 1500);
        })
        myPro.then(res => {
            console.log(res)
        }, err => {
            console.log(err)
        })
    </script>
</body>

</html>